package com.tbit.uqbike.webmanager.util;

import com.tbit.utils.DateTimeUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/**
 * 字符串实体类
 *
 * @author Leon
 * 2014-4-11 上午11:42:24
 */
public class StringUtil {

    private static final Pattern pattern = Pattern.compile(";");
    private static final Pattern commaPattern = Pattern.compile(",");
    // 16进制数字：大小写不影响
    private final static char[] HEXDIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    public String string;
    public Integer tmp;

    /**
     * 分解字符串(整形)，元素可重叠
     */
    public static List<Integer> getIntegerLists(String param) {
        if (null == param) {
            return new LinkedList<>();
        }

        return commaPattern.splitAsStream(param).map((x) -> Integer.parseInt(x))
                .collect(Collectors.toList());
    }

    public static Set<String> splitStr(String val) {
        if (StringUtils.isBlank(val)) {
            return Collections.emptySet();
        }
        return Arrays.stream(val.split(",")).collect(Collectors.toSet());
    }

    /**
     * 分解字符串(整形)，元素可重叠,根据分号分割
     */
    public static List<String> getList(String param) {
        if (null == param) {
            return new LinkedList<>();
        }

        return pattern.splitAsStream(param).collect(Collectors.toList());
    }

    /**
     * 分解字符串(整形),元素不可重叠
     */
    public static List<Integer> getIntegerList(String param) {
        if (null == param) {
            return new LinkedList<>();
        }
        String[] params = param.split(",");
        List<Integer> resultList = new ArrayList<Integer>();
        Map<Integer, Integer> map = new HashMap<>();
        for (String par : params) {
            try {
                Integer i = Integer.parseInt(par);
                if (!map.containsKey(i)) {
                    map.put(i, i);
                    resultList.add(i);
                }
            } catch (Exception e) {

            }
        }
        return resultList;
    }

    /**
     * 将字符串根据逗号分割，并统计每一个元素的数量且根据元素排序
     */
    public static TreeMap<String, Long> getListBySymbol(String s) {
        s = s.replaceAll(" +", "");
        TreeMap<String, Long> result = Arrays.stream(s.split(","))
                .sorted()
                .collect(Collectors.groupingBy(Function.identity(), TreeMap::new, Collectors.counting()));
        return result;
    }

    /**
     * 构造字符串
     */
    public static String getListString(List<Integer> ids) {
        StringBuffer result = new StringBuffer();

        for (int i = 0, length = ids.size(); i < length; i++) {
            result.append(ids.get(i));

            if (i != (length - 1)) {
                result.append(",");
            }
        }

        return result.toString();
    }

    /**
     * 构造字符串
     */
    public static String getArrayListString(List<String> paramList) {
        StringBuffer result = new StringBuffer();

        for (int i = 0, length = paramList.size(); i < length; i++) {
            result.append("'" + paramList.get(i) + "'");

            if (i != (length - 1)) {
                result.append(",");
            }
        }

        return result.toString();
    }

    /**
     * 构造HTTP字符串
     */
    public static String getArrayListStringHttp(List<String> paramList) {
        StringBuffer result = new StringBuffer();

        for (int i = 0, length = paramList.size(); i < length; i++) {
            result.append(paramList.get(i));

            if (i != (length - 1)) {
                result.append(",");
            }
        }

        return result.toString();
    }

    /**
     * 分解字符串（double）
     */
    public static List<Double> getDoubleList(String param) {
        String[] params = param.split(",");
        List<Double> resultList = new ArrayList<Double>();
        for (String par : params) {
            resultList.add(Double.parseDouble(par));
        }

        return resultList;
    }

    /**
     * 获取六位随机数
     *
     * @return
     */
    @SuppressWarnings("unchecked")
    public static String getAuthCode() {
        String str = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        @SuppressWarnings("rawtypes")
        List list = new ArrayList();
        while (sb.length() < 6) {
            int number = random.nextInt(10);
            if (sb.length() > 0 && !"0".equals(sb.substring(0, 1))) {
                int n = 0;
                for (int i = 0; i < list.size(); i++) {
                    if (!((Object) number).equals(list.get(i))) {
                        n++;
                    }
                }
                if (n == sb.length()) {
                    sb.append(str.charAt(number));
                    list.add(number);
                }
            } else {
                if (!"0".equals(String.valueOf(str.charAt(number)))
                        && sb.length() == 0) {
                    sb.append(str.charAt(number));
                    list.add(number);
                }
            }
        }

        return sb.toString();
    }

    public static boolean makeChecksum(String data) {
        if (data == null || "".equals(data)) {
            return false;
        }
        int total = 0;
        int len = data.length() - 2;
        int num = 0;
        while (num < len) {
            String s = data.substring(num, num + 2);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }
        /**
         * 用256求余最大是255，即16进制的FF
         */
        int mod = total % 256;
        String hex = Integer.toHexString(mod);
        String lastIndex = data.substring(len);
        len = hex.length();
        // 如果不够校验位的长度，补0,这里用的是两位校验
        if (len < 2) {
            hex = "0" + hex;
        }

        System.out.println(lastIndex);
        System.out.println(hex.toUpperCase());
        return hex.toUpperCase().equals(lastIndex);
    }

    public static String intToHex(int n) {
        StringBuffer s = new StringBuffer();
        String a;
        char[] b = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        while (n != 0) {
            s = s.append(b[n % 16]);
            n = n / 16;
        }
        a = s.reverse().toString();
        if (a.length() < 2) {
            a = "0" + a;
        }
        return a;
    }

    /**
     * 获取指定字符后的字符串
     */
    public static String getStrByLocation(String target, String symbol) {
        String str = target.substring(target.substring(0, target.indexOf(symbol)).length() + 1, target.length());
        return str;
    }

    public static int get(int num, int index) {
        return (num & (0x1 << index)) >> index;
    }

    /**
     * 将byte类型数字转成成16进制字符串
     *
     * @param b 表述范围
     * @return
     * @explain
     */
    public static String byteToHexString(byte b) {
        if (127 < b || b < -128) {
            return "";
        }
        // 确保n是正整数
        int n = b < 0 ? 256 + b : b;
        return "" + HEXDIGITS[n / 16] + HEXDIGITS[n % 16];
    }

    @Override
    public String toString() {
        return "StringUtil [string=" + string + ", tmp=" + tmp + "]";
    }

    /**
     * 获取骑行订单号
     *
     * @return
     */
    public static String getOrderNOByDate(Date date) {
        // 10位随机数
        return DateTimeUtil.getDateTimeyyyyMMdd(date) + getRandomString(6);
    }
    /**
     * 获取指定位数随机数
     *
     * @param number
     * @return
     */
    public static String getRandomString(int number) {
        StringBuilder result = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < number; i++) {
            result.append(random.nextInt(10));
        }

        return result.toString();
    }

//    public static void main(String[] args) throws UnsupportedEncodingException {
//        System.out.println(DateTimeUtil
//            .StringToDateTime("2020-06-25"+" 23:59:59").getTime()<=new Date().getTime());
//    }

}
